package com.zb.automation.util;

import javax.servlet.http.HttpServletRequest;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Description
 * @Author ZhangBin
 * @Data 2022/7/23 23:38
 */
public class UserAgentUtils {
    private static final String PHONE_PATTERN = "\\b(ip(hone|od)|android|opera m(ob|in)i|windows (phone|ce)|blackberry|s(ymbian|eries60|amsung)|p(laybook|alm|rofile/midp|laystation portable)|nokia|fennec|htc[-_]|mobile|up.browser|[1-4][0-9]{2}x[1-4][0-9]{2})\\b";
    private static final String TABLET_PATTERN = "\\b(ipad|tablet|(Nexus 7)|up.browser|[1-4][0-9]{2}x[1-4][0-9]{2})\\b";
    private static final Pattern phonePat = Pattern.compile("\\b(ip(hone|od)|android|opera m(ob|in)i|windows (phone|ce)|blackberry|s(ymbian|eries60|amsung)|p(laybook|alm|rofile/midp|laystation portable)|nokia|fennec|htc[-_]|mobile|up.browser|[1-4][0-9]{2}x[1-4][0-9]{2})\\b", 2);
    private static final Pattern tablePat = Pattern.compile("\\b(ipad|tablet|(Nexus 7)|up.browser|[1-4][0-9]{2}x[1-4][0-9]{2})\\b", 2);

    public UserAgentUtils() {
    }

    public static boolean isMobile(String userAgent) {
        if (null != userAgent && userAgent.trim().length() != 0) {
            Matcher matcherPhone = phonePat.matcher(userAgent);
            return matcherPhone.find();
        } else {
            return false;
        }
    }

    public static String getBrowser(HttpServletRequest request) {
        String userAgent = request.getHeader("USER-AGENT").toLowerCase();
        if (userAgent != null) {
            if (userAgent.indexOf("msie") >= 0) {
                return "IE";
            }

            if (userAgent.indexOf("firefox") >= 0) {
                return "FF";
            }

            if (userAgent.indexOf("safari") >= 0) {
                return "SF";
            }
        }

        return null;
    }
}
